/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.fee.web;

import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.utils.PrimaryGenerater;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.fee.entity.Consignor;
import com.jeeplus.modules.fee.entity.PayInvoice;
import com.jeeplus.modules.fee.entity.PayInvoiceDetail;
import com.jeeplus.modules.fee.entity.Payable;
import com.jeeplus.modules.fee.service.ConsignorService;
import com.jeeplus.modules.fee.service.PayInvoiceDetailService;
import com.jeeplus.modules.fee.service.PayInvoiceService;
import com.jeeplus.modules.fee.service.PayableService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 应收发票Controller
 * @author weisong
 * @version 2017-09-19
 */
@Controller
@RequestMapping(value = "${adminPath}/fee/payInvoice")
public class PayInvoiceController extends BaseController {

	@Autowired
	private PayInvoiceService payInvoiceService;
	@Autowired
	private PayableService payableService;
	@Autowired
	private ConsignorService consignorService;
	@Autowired
	private PayInvoiceDetailService payInvoiceDetailService;

	@ModelAttribute
	public PayInvoice get(@RequestParam(required=false) String id) {
		PayInvoice entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = payInvoiceService.get(id);
		}
		if (entity == null){
			entity = new PayInvoice();
		}
		return entity;
	}
	
	/**
	 * 应收发票列表页面
	 */
	@RequiresPermissions("fee:payInvoice:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/fee/payInvoiceList";
	}
	
		/**
	 * 应收发票列表数据
	 */
	@ResponseBody
	@RequiresPermissions("fee:payInvoice:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(PayInvoice payInvoice, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<PayInvoice> page = payInvoiceService.findPage(new Page<PayInvoice>(request, response), payInvoice); 
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑应收发票表单页面
	 */
	@RequiresPermissions(value={"fee:payInvoice:view","fee:payInvoice:add","fee:payInvoice:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(PayInvoice payInvoice, Model model) {
		model.addAttribute("payInvoice", payInvoice);
		if(StringUtils.isBlank(payInvoice.getId())){//如果ID是空为添加
			model.addAttribute("isAdd", true);
		}
		List<PayInvoiceDetail> list = payInvoiceDetailService.findPayInvoiceDetailById(payInvoice.getId());
		if (null != list && list.size() > 0) {
			model.addAttribute("list", list);
			model.addAttribute("flag", "invoice");
		}
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		model.addAttribute("target", request.getParameter("target"));
		//来自付款单form页面查看的标记
		String different = request.getParameter("different");
		if (null != different && different != "") {
			model.addAttribute("different", different);
		}
		return "modules/fee/payInvoiceForm";
	}

	/**
	 * 保存应收发票
	 */
	@RequiresPermissions(value={"fee:payInvoice:add","fee:payInvoice:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(PayInvoice payInvoice, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, payInvoice)){
			return form(payInvoice, model);
		}
		if (!payInvoice.getIsNewRecord()) {// 编辑表单保存
			PayInvoice t = payInvoiceService.get(payInvoice.getId());// 从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(payInvoice, t);// 将编辑表单中的非NULL值覆盖数据库记录中的值
			payInvoiceService.save(t);// 保存
			// 保存到发票明细表
			String ids = request.getParameter("ids"); // 将form页面取的id值循环遍历
			saveInvoiceDetail(payInvoice,ids);
			addMessage(redirectAttributes, "保存应收发票成功");
		} else {// 新增表单保存
			String ids= request.getParameter("ids");	//将form页面取的id值循环遍历
			//判断子表是否有数据，没有数据不能保存
			if (StringUtils.isEmpty(ids) || StringUtils.isEmpty(ids.trim().replaceAll(",",""))) {
				addMessage(redirectAttributes, "请引入发票明细表");
			} else {
				//生成单号
				String number = "";
				PayInvoice pay = payInvoiceService.findInvoiceNoAndInvoiceDate();
				Format format1 = new SimpleDateFormat("yyyyMMdd");    //初始化时间格式
				//比较结算日期是否和现在的日期相等
				if (null == pay) {
					number = PrimaryGenerater.getInstance().generaterNextNumber("YFFP", null);
				} else {
					if (String.valueOf(format1.format(pay.getInvoiceDate())).equals(String.valueOf(format1.format(new Date())))) {
						number = PrimaryGenerater.getInstance().generaterNextNumber("YFFP", pay.getInvoiceNo());
					} else {
						number = PrimaryGenerater.getInstance().generaterNextNumber("YFFP", null);
					}
				}
				payInvoice.setInvoiceNo(number);
				String[] _ids = ids.split(","); // 将form页面取的id值循环遍历
				String payableIds = "";
				//获取应付结算单id
				if(_ids.length>0){
					for (String id : _ids) {
						if (StringUtils.isNotEmpty(id)) {
							String [] tempPay = id.split("_"); // 123_200
							if(tempPay.length>0){
								payableIds += tempPay[0]+",";
							}
						}
					}
				}
				payInvoice.setFeePayable(payableIds);
				payInvoiceService.save(payInvoice);// 保存
				//保存应收发票子表
				saveInvoiceDetail(payInvoice,ids);
				addMessage(redirectAttributes, "保存应收发票成功");
				String type = request.getParameter("typeTarget");
				System.out.println(type);
				if (null != type) {
					if (type.equals("payableList")) {
						return "redirect:" + Global.getAdminPath() + "/fee/payable/list";
					} else {
						return "redirect:" + Global.getAdminPath() + "/fee/payInvoice/?repage";
					}
				}
			}
		}
		return "redirect:"+Global.getAdminPath()+"/fee/payInvoice/?repage";
	}
	
	/**
	 * 删除应收发票
	 */
	@ResponseBody
	@RequiresPermissions("fee:payInvoice:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(PayInvoice payInvoice, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		payInvoiceService.delete(payInvoice);
		j.setMsg("删除应收发票成功");
		return j;
	}
	
	/**
	 * 批量删除应收发票
	 */
	@ResponseBody
	@RequiresPermissions("fee:payInvoice:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			//根据应付发票id查询应付发票明细表
			PayInvoiceDetail payInvoiceDetail = new PayInvoiceDetail();
			payInvoiceDetail.setFeePayInvoice(payInvoiceService.get(id));
			List<PayInvoiceDetail> list = payInvoiceDetailService.findList(payInvoiceDetail);
			for (int i = 0; i < list.size(); i++) {
				//删除应付发票明细表
				payInvoiceDetailService.delete(list.get(i));
			}
			payInvoiceService.delete(payInvoiceService.get(id));
		}
		j.setMsg("删除应收发票成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("fee:payInvoice:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(PayInvoice payInvoice, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "应收发票"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<PayInvoice> page = payInvoiceService.findPage(new Page<PayInvoice>(request, response, -1), payInvoice);
    		new ExportExcel("应收发票", PayInvoice.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出应收发票记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("fee:payInvoice:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<PayInvoice> list = ei.getDataList(PayInvoice.class);
			for (PayInvoice payInvoice : list){
				try{
					payInvoiceService.save(payInvoice);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条应收发票记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条应收发票记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入应收发票失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fee/payInvoice/?repage";
    }
	
	/**
	 * 下载导入应收发票数据模板
	 */
	@RequiresPermissions("fee:payInvoice:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "应收发票数据导入模板.xlsx";
    		List<PayInvoice> list = Lists.newArrayList(); 
    		new ExportExcel("应收发票数据", PayInvoice.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fee/payInvoice/?repage";
    }

	/**
	 * 获取弹出窗口的数据
	 */
	@RequestMapping(value = "findAllPayableList")
	public
	@ResponseBody
	List<Payable> findAllPayableList(Payable feePayable, HttpServletRequest request, HttpServletResponse response) {
		// 判断应付结算单的状态【已确认，部分开票，部分核销】
		String _status = request.getParameter("status");
		//获input框输入的值[模糊查询]
		String clearUnit = request.getParameter("clearUnit");
		if (_status != null) {
			Integer status = Integer.parseInt(_status);
			feePayable.setStatus(status);
		}
		if (StringUtils.isNotEmpty(clearUnit)) {
			Consignor f = new Consignor();
			f.setName(clearUnit);
			feePayable.setPayee(f);//结算方
		}
		List<Payable> list = payableService.findList(feePayable);
		return list;
	}

	/**
	 * 根据属性和值获取信息
	 */
	@RequestMapping(value="findInvoicePropertyByName")
	public @ResponseBody Consignor findInvoicePropertyByName(HttpServletRequest request, HttpServletResponse response, Model model){
		String name = request.getParameter("name");
		String value = request.getParameter("propertyValue");
		Consignor feeConsignor = new Consignor();
		if(null!=name && name != "" && null!=value && value != ""){
			feeConsignor = consignorService.findUniqueByProperty(name,value);
		}
		return feeConsignor;
	}

	/**
	 * 保存发票子表
	 */
	public void saveInvoiceDetail(PayInvoice payInvoice,String ids){
		// 保存到发票明细表
		String[] _ids = ids.split(","); // 将form页面取的id值循环遍历
		PayInvoiceDetail fpd = null;
		String[] str = null;
		if (_ids.length != 0) {
			for (String id : _ids) {
				if (StringUtils.isNotEmpty(id)) {
					fpd = new PayInvoiceDetail();
					str = id.split("_"); // 123 200
					// System.out.println(str.length+"===========================");
					if (StringUtils.isNotEmpty(str[0])) {
						Payable payble = payableService.get(str[0]);
						fpd.setFeePayable(payble);
						fpd.setClearingNo(payble.getClearingNo());
						fpd.setClearingMoney(payble.getClearingMoney());
						if (null == payble.getInvoiceMoney()) {
							fpd.setInvoiceMoney(0.0);
						} else {
							fpd.setInvoiceMoney(payble.getInvoiceMoney());
						}
					}
					if (StringUtils.isNotEmpty(str[1])) {
						fpd.setInvMoney(Double.parseDouble(str[1]));
					}
					fpd.setFeePayInvoice(payInvoice);
					payInvoiceDetailService.save(fpd);
				}
			}
		}
	}

	/**
	 * 删除应付发票明细
	 * @param id 应付发票子表id
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "removePayInvoiceDetail")
	public String removePayInvoiceDetail(String id, RedirectAttributes redirectAttributes) {
		PayInvoiceDetail feePayInvoiceDetail = payInvoiceDetailService.get(id);	//根据id查询数据
		//获取本次开票金额
		Double detailInvMoney = feePayInvoiceDetail.getInvMoney();
		//根据发票子表的feePayInvoice的属性获取发票主表
		PayInvoice feePayInvoice = payInvoiceService.get(feePayInvoiceDetail.getFeePayInvoice());
		//获取发票主表的开票金额
		Double invoiceMoney = feePayInvoice.getInvoiceMoney();
		//更新发票主表的开票金额[发票主表的总开票金额-发票子表的本次开票金额]
		if (null != detailInvMoney && null != invoiceMoney) {
			feePayInvoice.setInvoiceMoney((invoiceMoney-detailInvMoney));
			payInvoiceService.save(feePayInvoice);
		}
		payInvoiceDetailService.delete(feePayInvoiceDetail);
		addMessage(redirectAttributes, "删除应付发票明细成功");
		return "redirect:"+Global.getAdminPath()+"/fee/payInvoice/form?id="+feePayInvoice.getId();
	}

	/**
	 * 修改应付发票状态
	 */
	@RequestMapping(value = "updateStatus")
	public
	@ResponseBody AjaxJson updateStatus(String ids,HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray) {
			PayInvoice feePayInvoice = new PayInvoice();
			feePayInvoice.setId(id);
			List<PayInvoice> list = payInvoiceService.findList(feePayInvoice);
			payInvoiceService.updateVcaMoneyAndStatusById(null, PayInvoice.updateStatus3, id);
			// 回填应付账款[确认之后回填应付结算单]
			List<PayInvoiceDetail> list1 = payInvoiceDetailService.findPayInvoiceMoney(id);
			for (int i = 0; i < list1.size(); i++) {
				PayInvoiceDetail detail = list1.get(i);
				Payable payble = payableService.get(detail.getFeePayable());
				double invoiceMoney = detail.getInvoiceMoney();
				double clearMoney = detail.getClearingMoney();
				// System.out.println(invoiceMoney == clearMoney);
				if (payble.getStatus() < Payable.updateStatus4) {//判断状态是否小于部分核销
					if (invoiceMoney == clearMoney) {//全部开票[未开票金额=0]
						payableService.updateMoneyAndStatusById(Payable.updateStatus2, invoiceMoney,
								null, 0.0, clearMoney - (payble.getVcaMoney() == null ? 0 : payble.getVcaMoney()), detail.getFeePayable().getId());
					} else {//部分开票
						payableService.updateMoneyAndStatusById(Payable.updateStatus1, invoiceMoney,
								null, clearMoney - invoiceMoney, clearMoney - (payble.getVcaMoney() == null ? 0 : payble.getVcaMoney()), detail.getFeePayable().getId());
					}
				} else {//部分核销状态不变，回填开票金额
					payableService.updateMoneyAndStatusById(null, invoiceMoney,
							null, clearMoney - invoiceMoney, clearMoney - payble.getVcaMoney(), detail.getFeePayable().getId());
				}
			}
		}
		j.setMsg("应收发票状态修改成功");
		return j;
	}

	/**
	 * 修改应付发票状态
	 */
	@RequestMapping(value = "updateStatusTwo")
	public String updateStatusTwo(String id,HttpServletRequest request) {
		payInvoiceService.updateVcaMoneyAndStatusById(null, PayInvoice.updateStatus3, id);
		// 回填应付账款[确认之后回填应付结算单]
		List<PayInvoiceDetail> list1 = payInvoiceDetailService.findPayInvoiceMoney(id);
		for (int i = 0; i < list1.size(); i++) {
			PayInvoiceDetail detail = list1.get(i);
			Payable payble = payableService.get(detail.getFeePayable());
			double invoiceMoney = detail.getInvoiceMoney();
			double clearMoney = detail.getClearingMoney();
			// System.out.println(invoiceMoney == clearMoney);
			if (payble.getStatus() < Payable.updateStatus4) {//判断状态是否小于部分核销
				if (invoiceMoney == clearMoney) {//全部开票[未开票金额=0]
					payableService.updateMoneyAndStatusById(Payable.updateStatus2, invoiceMoney,
							null, 0.0, clearMoney - (payble.getVcaMoney() == null ? 0 : payble.getVcaMoney()), detail.getFeePayable().getId());
				} else {//部分开票
					payableService.updateMoneyAndStatusById(Payable.updateStatus1, invoiceMoney,
							null, clearMoney - invoiceMoney, clearMoney - (payble.getVcaMoney() == null ? 0 : payble.getVcaMoney()), detail.getFeePayable().getId());
				}
			} else {//部分核销状态不变，回填开票金额
				payableService.updateMoneyAndStatusById(null, invoiceMoney,
						null, clearMoney - invoiceMoney, clearMoney - payble.getVcaMoney(), detail.getFeePayable().getId());
			}
		}
		return "redirect:" + Global.getAdminPath() + "/fee/payInvoice/form?id=" + id;
	}

	/**
	 * 核销操作(跳转到新增付款单页面)
	 */
	@RequestMapping(value = "verificOperation")
	public String verificOperation(@RequestParam String ids, @RequestParam Integer type, Model model, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		// 如果ids为空，则跳转到feeReceivablesForm
		String url = "/fee/payInvoice/?repage";
		if (StringUtils.isNotEmpty(ids)) { // 判断ids是否为空
			String[] _ids = ids.split(",");
			List<PayInvoiceDetail> list = new ArrayList<PayInvoiceDetail>();
			PayInvoiceDetail tempDetail = new PayInvoiceDetail();
			for (String id : _ids) {
				if (StringUtils.isNotEmpty(id)) {
					tempDetail = new PayInvoiceDetail();
					PayInvoice invoice = payInvoiceService.get(id);
					tempDetail.setFeePayInvoice(invoice);
					List<PayInvoiceDetail> detail = payInvoiceDetailService.findList(tempDetail);
					list.addAll(detail);
					System.out.println(list);
				}
			}
			redirectAttributes.addFlashAttribute("list", list);
			redirectAttributes.addFlashAttribute("sign", "invoice");
			redirectAttributes.addFlashAttribute("ids", ids);
			redirectAttributes.addFlashAttribute("type", type);
			String target = request.getParameter("target")==null ? "invoice" : "paymentList";
			url = "/fee/payment/form?target="+target+"&ids="+ids;
		}
		return "redirect:" + Global.getAdminPath() + url;
	}



}